package com.coocaa.app.gamecenter.pages.arsenal;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coocaa.app.gamecenter.framework.GameCenterActivity;
import com.coocaa.app.gamecenter.framework.ui.GameCenterBaseLayout;
import com.coocaa.app.gamecenter.pages.arsenal.data.ArsenalData;
import com.coocaa.app.gamecenter.pages.arsenal.view.ArsenalGridView;
import com.coocaa.app.gamecenter.pages.arsenal.view.ItemListView;
import com.coocaa.app.gamecenter.pages.arsenal.view.polygonView;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.uipackage.utils.CoocaaFresco;
import com.coocaa.x.uipackage.widget.CoocaaDraweeView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.tianci.appstore.R;
import com.tianci.appstore.utils.AsyncTask;
import com.tianci.appstore.utils.SkyConstants;

/**
 * Created by xfk on 2015/11/4.
 */
public class ArsenalLayout extends GameCenterBaseLayout implements ItemListView.ItemEventChangeInterface {
    private static String tag = "arsenal";
    private RelativeLayout mContentView;
    private RelativeLayout leftPostersView;
    private FrameLayout fullScreenLayout;
    private ArsenalGridView mArsenalGridView;
    private String previewImgUrl;
    private String fullScreenUrl;
    private String previewControlId;
    private String fullScreenControlId;
    private CoocaaDraweeView previewView;
    private CoocaaDraweeView fullScreenView;
    private TextView errorTextView = null;
    private ImageView mLoading = null;
    private ImageView mLeftPostersLoading = null;

    public ArsenalLayout(Context context) {
        super(context);
        this.hideFocusView();
        createContentView();
        createLeftPosters();
        createGridView();
    }

    @Override
    public View getContentView() {
        return null;
    }

    private void createContentView() {
        mContentView = new RelativeLayout(mContext);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(Div(1703), Div(992),
                Gravity.TOP);
        params.leftMargin = Div(148);
        params.topMargin = Div(42);
        addView(mContentView, params);
        createFullScreenImgView();
    }

    private void createLeftPosters () {
        if(mContentView == null)
            return;

        leftPostersView = new RelativeLayout(mContext);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(734),
                CoocaaApplication.Div(888));
        params.leftMargin = 0;
        params.topMargin = Div(94);

        mContentView.addView(leftPostersView, params);

        polygonView mpolygonView = new polygonView(mContext, null);
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        leftPostersView.addView(mpolygonView, params1);
    }

    private void createGridView() {
        mArsenalGridView = new ArsenalGridView(mContext);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(968),
                LayoutParams.MATCH_PARENT);
        params.leftMargin = CoocaaApplication.Div(790);
        params.topMargin = CoocaaApplication.Div(46);
        mArsenalGridView.setItemEventChangeInterface(this);
        mContentView.addView(mArsenalGridView, params);
    }

    private void createFullScreenImgView() {
        fullScreenLayout = new FrameLayout(mContext);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        View contentView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content);
        if(contentView instanceof  FrameLayout) {
            ((FrameLayout)contentView).addView(fullScreenLayout, params);
        }

        fullScreenLayout.setVisibility(View.GONE);
    }

    public void refreshUI(ArsenalData arsenalData) {
        if(mArsenalGridView != null) {
            mArsenalGridView.refreshUI(arsenalData);
        }
    }

    private CoocaaDraweeView setImageUrl(String url, int w, int h, Postprocessor processor) {
          try {
            String path = url;
              CoocaaDraweeView mSimpleDraweeView = new CoocaaDraweeView(mContext);
            mSimpleDraweeView
                    .getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_INSIDE);
            if(processor == fullScreenPicPostprocessor) {
            mSimpleDraweeView
                    .getHierarchy().setPlaceholderImage(R.drawable.bg);
            }
            Uri uri = Uri.parse(path);
            int width = w, height = h;
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                    .setProgressiveRenderingEnabled(true)
                    .setPostprocessor(processor)
                    .setResizeOptions(new ResizeOptions(width, height))
                    .build();
            PipelineDraweeController controller = (PipelineDraweeController)
                    CoocaaFresco.newDraweeControllerBuilder(mContext)
                              .setImageRequest(request)
                              .setControllerListener(controllerListener)
                              .setOldController(mSimpleDraweeView.getController())
                                      // other setters as you need
                              .build();
            mSimpleDraweeView.setController(controller);
            if(processor == redMeshPostprocessor) {
                previewControlId = controller.getId();
                LogUtils.i(tag, "previewControlId : " + previewControlId);
            } else {
                fullScreenControlId = controller.getId();
                LogUtils.i(tag, "fullScreenControlId : " + fullScreenControlId);
            }

            RoundingParams roundingParams = RoundingParams.fromCornersRadius(0.1f);
            mSimpleDraweeView.getHierarchy().setRoundingParams(roundingParams);

            return mSimpleDraweeView;
        } catch (NullPointerException e) {
            LogUtils.i("category", "" + e);
        }

        return null;
    }

    Postprocessor redMeshPostprocessor = new BasePostprocessor() {
        @Override
        public String getName() {
            return "redMeshPostprocessor";
        }

        @Override
        public void process(Bitmap bitmap) {

            for (int x = bitmap.getWidth() - 100; x < bitmap.getWidth(); x++) {
                for (int y = 0; y < (x - bitmap.getWidth() + 100); y++) {
                        bitmap.setPixel(x, y, Color.TRANSPARENT);
                }
            }

            for (int x = 0; x < 100; x++) {
                for (int y = bitmap.getHeight() - 100 + x; y < bitmap.getHeight(); y++) {
                        bitmap.setPixel(x, y, Color.TRANSPARENT);
                }
            }

            LogUtils.i(tag, "get bitmap end");
        }
    };

    Postprocessor fullScreenPicPostprocessor = new BasePostprocessor() {
        @Override
        public String getName() {
            return "redMeshPostprocessor";
        }

        @Override
        public void process(Bitmap bitmap) {
            LogUtils.i("1109", "get bitmap");
            hideloading();
            ((GameCenterActivity)mContext).cancelSlowNetTimer();
        }
    };
    
    ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
        @Override
        public void onSubmit(String s, Object o) {
            LogUtils.i(tag, "sunny facebook onSubmit s:" + s);

        }

        @Override
        public void onFinalImageSet(String s, ImageInfo o, Animatable animatable) {
            LogUtils.i(tag, "sunny facebook onFinalImageSet s:" + s + ";   o:" + o.toString());
            if(previewView != null && previewControlId != null && previewControlId.equals(s)) {
                hideLeftPostersLoading();
            }
        }

        @Override
        public void onIntermediateImageFailed(String s, Throwable throwable) {
            LogUtils.i(tag, "sunny facebook onIntermediateImageFailed s:" + s + ";   throwable:" + throwable.toString());
        }

        @Override
        public void onFailure(String s, Throwable throwable) {
            LogUtils.i(tag, "sunny facebook onFailure s:" + s + ";   throwable:" + throwable.toString());

            if(s != null && fullScreenControlId != null
                    && s.equals(fullScreenControlId)) {
                hideloading();
                ((GameCenterActivity)mContext).cancelSlowNetTimer();
                if (!Android.isNetConnected(mContext)) {
                    setLoadDataErrorMsg(mContext.getString(R.string.connection_more_wonderful));
                } else {
                    setLoadDataErrorMsg(mContext.getString(R.string.no_app_list));
                }
            }

        }

        @Override
        public void onRelease(String s) {
            LogUtils.i(tag, "sunny facebook onRelease s:" + s);
        }
    };

    @Override
    public void itemFocusChange(String imgUrl) {
        previewImgUrl = imgUrl;
        AsyncTask.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLeftPostersloading();
                if(previewView != null) {
                    leftPostersView.removeView(previewView);
                    try {
                        previewView.setDrawingCacheEnabled(true);
                        if(previewView.getDrawingCache() != null)
                            previewView.getDrawingCache().recycle();
                    } catch (RuntimeException e) {
                        LogUtils.i(tag, e.toString());
                    } finally {
                        previewView.destroyDrawingCache();
                        previewView = null;
                    }
                }

                previewView = setImageUrl(previewImgUrl, CoocaaApplication.Div(724), CoocaaApplication.Div(826), redMeshPostprocessor);
                if(previewView == null)
                {
                    return;
                }
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(724),
                        CoocaaApplication.Div(826));
                params.leftMargin = CoocaaApplication.Div(5);
                params.topMargin = CoocaaApplication.Div(5);
                leftPostersView.addView(previewView, params);
            }
        });
    }

    @Override
    public boolean itemOnKeyDown(int keyCode) {

        if(fullScreenLayout.getVisibility() == VISIBLE
                && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
                || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
                || keyCode == KeyEvent.KEYCODE_DPAD_UP
                || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
                || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
            return true;
        }

        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(fullScreenLayout.getVisibility() == View.VISIBLE) {
                fullScreenLayout.setVisibility(GONE);
                if(fullScreenView != null) {
                    fullScreenLayout.removeView(fullScreenView);
                    try {
                        fullScreenView.setDrawingCacheEnabled(true);
                        if(fullScreenView.getDrawingCache() != null)
                            fullScreenView.getDrawingCache().recycle();

                        if(errorTextView != null) {
                            fullScreenLayout.removeView(errorTextView);
                            errorTextView.destroyDrawingCache();
                            errorTextView = null;
                        }

                        ((GameCenterActivity)mContext).cancelSlowNetTimer();
                    } catch (RuntimeException e) {
                        LogUtils.i(tag, e.toString());
                    } finally {
                        fullScreenView.destroyDrawingCache();
                        fullScreenView = null;
                    }
                }

                hideloading();
                return true;
            }
        }

        return false;
    }

    protected void showloading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLoading == null) {
                    mLoading = new ImageView(mContext);
                    mLoading.setBackgroundResource(R.anim.game_center_loading);
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            SkyConstants.Div(180), SkyConstants.Div(180), Gravity.CENTER);
                    fullScreenLayout.addView(mLoading, params);
                    params.leftMargin = 0;
                    mLoading.setVisibility(View.GONE);
                }

                if (mLoading.getVisibility() != View.VISIBLE) {
                    mLoading.setVisibility(View.VISIBLE);
                    AnimationDrawable drawable = (AnimationDrawable) mLoading.getBackground();
                    if (drawable != null) {
                        drawable.start();
                    }
                }

                mLoading.bringToFront();
            }
        });

    }

    protected void showLeftPostersloading() {

        if (mLeftPostersLoading == null) {
            mLeftPostersLoading = new ImageView(mContext);
            mLeftPostersLoading.setBackgroundResource(R.anim.game_center_loading);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_HORIZONTAL);
            params.addRule(RelativeLayout.CENTER_VERTICAL);
            leftPostersView.addView(mLeftPostersLoading, params);
            params.leftMargin = 0;
            mLeftPostersLoading.setVisibility(View.GONE);
        }

        if (mLeftPostersLoading.getVisibility() != View.VISIBLE) {
            mLeftPostersLoading.setVisibility(View.VISIBLE);
            AnimationDrawable drawable = (AnimationDrawable) mLeftPostersLoading.getBackground();
            if (drawable != null) {
                drawable.start();
            }
        }
        mLeftPostersLoading.bringToFront();
    }


    protected void hideloading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLoading != null) {
                    AnimationDrawable drawable = (AnimationDrawable) mLoading.getBackground();
                    if (drawable != null) {
                        drawable.stop();
                    }
                    mLoading.setVisibility(View.GONE);
                }
            }
        });
    }

    protected void hideLeftPostersLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mLeftPostersLoading != null) {
                    AnimationDrawable drawable = (AnimationDrawable) mLeftPostersLoading.getBackground();
                    if (drawable != null) {
                        drawable.stop();
                    }
                    mLeftPostersLoading.setVisibility(View.GONE);
                }
            }
        });
    }

    protected void setLoadDataErrorMsg(final String error) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (errorTextView == null) {
                    errorTextView = new TextView(mContext);
                    errorTextView.setTextColor(Color.WHITE);
                    errorTextView.setTextSize(SkyConstants.Dpi(48));
                    fullScreenLayout.addView(errorTextView, new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
                }
                errorTextView.setVisibility(VISIBLE);
                errorTextView.setText(error);
            }
        });
    }
    @Override
    public void itemClick(String bigImgUrl) {
        LogUtils.i(tag, "itemClick: " + bigImgUrl);
        fullScreenUrl = bigImgUrl;
        AsyncTask.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fullScreenLayout.setVisibility(VISIBLE);
                if (fullScreenView != null) {
                    fullScreenLayout.removeView(fullScreenView);
                    try {
                        fullScreenView.setDrawingCacheEnabled(true);
                        if(fullScreenView.getDrawingCache() != null)
                            fullScreenView.getDrawingCache().recycle();
                    } catch (RuntimeException e) {
                        LogUtils.i(tag, e.toString());
                    } finally {
                        fullScreenView.destroyDrawingCache();
                        fullScreenView = null;
                    }
                }

                fullScreenView = setImageUrl(fullScreenUrl, CoocaaApplication.Div(1920), CoocaaApplication.Div(1080), fullScreenPicPostprocessor);
                LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                if (fullScreenView != null)
                    fullScreenLayout.addView(fullScreenView, params);

                showloading();
                ((GameCenterActivity)mContext).startSlowNetTimerDalay(7000);
            }
        });
    }

    public void onDestroy() {
        if(leftPostersView != null) {
            leftPostersView.removeAllViews();
            leftPostersView.destroyDrawingCache();
            leftPostersView = null;
        }

        if(fullScreenLayout != null) {
            fullScreenLayout.removeAllViews();
            fullScreenLayout.destroyDrawingCache();
            fullScreenLayout = null;
        }

        if(fullScreenView != null) {
            try {
                fullScreenView.setDrawingCacheEnabled(true);
                if(fullScreenView.getDrawingCache() != null)
                    fullScreenView.getDrawingCache().recycle();
            } catch (RuntimeException e) {
                LogUtils.i(tag, e.toString());
            } finally {
                fullScreenView.destroyDrawingCache();
                fullScreenView = null;
            }
        }

        if (mLoading != null) {
            Drawable drawable = mLoading.getBackground();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            mLoading = null;
        }

        if (mLeftPostersLoading != null) {
            Drawable drawable = mLeftPostersLoading.getBackground();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            mLeftPostersLoading = null;
        }

        if(previewView != null) {
            try {
                previewView.setDrawingCacheEnabled(true);
                if(previewView.getDrawingCache() != null)
                    previewView.getDrawingCache().recycle();
            } catch (RuntimeException e) {
                LogUtils.i(tag, e.toString());
            } finally {
                previewView.destroyDrawingCache();
                previewView = null;
            }
        }

        if(mContentView != null) {
            mContentView.removeAllViews();
            mContentView.destroyDrawingCache();
            mContentView = null;
        }
        if(mArsenalGridView != null) {
            mArsenalGridView.onDestroy();
            mArsenalGridView.destroyDrawingCache();
            mArsenalGridView = null;
        }
    }
}
